#include "./../../../include/online/CacheSystem/CacheManager.h"
#include "./../../../include/online/Tools/Configuration.h"
#include "./../../../include/online/Tools/MyLogger.h"

// 单例模式，确保全局唯一实例
CacheManager *CacheManager::_pInstance = nullptr;
pthread_once_t CacheManager::_once = PTHREAD_ONCE_INIT;

// 获取 CacheManager 实例
CacheManager *CacheManager::getInstance()
{
    pthread_once(&_once, init_r);
    return _pInstance;
}

// 获取 Key 缓存
LRUCache &CacheManager::getKeyCache(int index)
{
    return _keyCaches[index];
}

// 初始化缓存
void CacheManager::initCache(size_t threadNums, const string &keyPath)
{
    _keyCaches.resize(threadNums);
    for (auto &cache : _keyCaches)
    {
        cache.readFromFile(keyPath); // 读取 Key 缓存数据
    }
}

void CacheManager::periodicUpdateCaches()
{
    LRUCache allCache = _keyCaches[0];
    for (size_t i = 1; i != _keyCaches.size(); ++i)
    {
        auto &pendingList = _keyCaches[i].getPendingUpdateList(); // 获取待更新数据
        for (auto &it : pendingList)
        {
            allCache.put_insert(it.first, it.second); // 更新主缓存
        }
        pendingList.clear(); // 清空已同步的数据，防止重复
    }
    // 先全部放到0的更新列表里
    // 然后在更新他们几个
    for (size_t i = 0; i != _keyCaches.size(); ++i)
    {
        _keyCaches[i].update(allCache);
    }
    // 写入缓存文件
    _keyCaches.back().writeToFile(Configuration::getInstance()->getMapValue("keyCacheFile")); // 写入文件
}

// 构造函数，从配置文件初始化缓存
CacheManager::CacheManager()
{
    unordered_map<string, string> configMap = Configuration::getInstance()->getConfigMap();
    size_t threadNums = std::stoull(configMap["threadNums"]);
    initCache(threadNums, configMap["keyCacheFile"]);
}

// 析构函数
CacheManager::~CacheManager()
{
}

// 初始化单例
void CacheManager::init_r()
{
    if (_pInstance == nullptr)
    {
        _pInstance = new CacheManager();
        atexit(destroy);       // 程序退出时释放资源
    }
}

// 销毁单例
void CacheManager::destroy()
{
    if (_pInstance)
    {
        delete _pInstance;
        _pInstance = nullptr;
    }
}
